//
//  GIFImageSourceHelper.swift
//  GifUsage
//
//  Created by Ting Han on 2020/12/18.
//  Copyright © 2020 Ting Han. All rights reserved.
//

import ImageIO
import MobileCoreServices
import UIKit

// 默认的frameRate帧率 1s显示15帧
private let defaultFrameRate: Double = 15.0
private let defaultFrameDuration: Double = 1 / defaultFrameRate
// capDuration 临界值 （ulpOfOne浮点的最后位置）
private let capDurationThreshold: Double = 0.02 - Double.ulpOfOne
// 当frameDuration低于临界值时，使用minFrameDuration
private let minFrameDuration: Double = 0.1

/// 计算frameDuration
func CGImageSourceFrameDuration(imageSource: CGImageSource, atIndex index: Int) -> TimeInterval {
    guard imageSource.isGIF else { return 0.0 }
    
    guard let properties = imageSource.properties(at: index), let frameDuration = frameDuration(properties) else {
        return defaultFrameDuration
    }
    
    return frameDuration < capDurationThreshold ? minFrameDuration : frameDuration
}

private  func frameDuration(_ properties: GIFProperties) -> Double? {
    guard let unclampedDelayTime = properties[kCGImagePropertyGIFUnclampedDelayTime as String], let delayTime = properties[kCGImagePropertyGIFDelayTime as String] else { return nil }
    // 因为只用其中一个有可能会导致gif过快/过慢
    if unclampedDelayTime >= 0 {
        return unclampedDelayTime
    }
    return delayTime
}
typealias GIFProperties = [String: Double]

extension CGImageSource {
    var isGIF: Bool {
        let isTypeGIF = UTTypeConformsTo(CGImageSourceGetType(self) ?? "" as CFString, kUTTypeGIF)
        let count = CGImageSourceGetCount(self)
        return isTypeGIF && count > 0
    }
    
    func properties(at index: Int) -> GIFProperties? {
        guard let imageProperties = CGImageSourceCopyPropertiesAtIndex(self, index, nil) as? [String: AnyObject] else { return nil }
        return imageProperties[String(kCGImagePropertyGIFDictionary)] as? GIFProperties
    }
}
